package com.ld.admin.service.system;

import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.ld.admin.model.system.SysSensitiveWordModel;
import com.ld.common.service.ProjectBasicService;
import com.ld.shieldsb.annotation.util.TableNameUtil;
import com.ld.shieldsb.common.core.model.PageBean;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.reflect.ClassUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.core.util.properties.PropertiesPojo;
import com.ld.shieldsb.common.core.util.sensitiveWord.SensitiveWordResult;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.PageNavigationBean;
import com.ld.shieldsb.dao.model.QueryModel;
import com.ld.shieldsb.sensitiveword.DictionaryItem;
import com.ld.shieldsb.sensitiveword.SensitiveWordHandlerUtil;
import com.ld.shieldsb.sensitiveword.service.SensitiveWordService;
import com.ld.shieldsb.sensitiveword.service.SensitiveWordServiceFactory;
import com.ld.shieldsb.sensitiveword.service.SensitiveWordServiceType;

/**
 * 
 * 敏感词服务类，@Service注解用于自动注入
 * 
 * @ClassName SysTimedtaskService
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年01月04日 14:29:47
 *
 */
@Service
public class SysSensitiveWordSetService extends ProjectBasicService {
    static {
        // 注册实现类
        SensitiveWordServiceFactory.getInstance().registerServiceClass(SensitiveWordServiceType.DATABASE.getValue(),
                SensitiveWordDBService.class);
    }

    // 用于子类覆盖，扩展doSearch方法中QueryModel的处理（标准queryModel处理完，查询进行前的处理）
    @Override
    protected QueryModel extendDealQuery(QueryModel queryModel) {
        return super.extendDealQuery(queryModel);
    }

    // 用于子类覆盖，扩展doSearch方法中PageNavigationBean的处理（查询完成后进行）
    @Override
    protected <T> PageNavigationBean<T> extendDealPageNavigationBean(PageNavigationBean<T> pageNavigationBean) {
        return super.extendDealPageNavigationBean(pageNavigationBean);
    }

    // 删除方法子类扩展（删除完成后进行）
    @Override
    protected <T> boolean extendRemove(Boolean flag, Class<T> classOfT, String key, Object value, Integer status, Long userId) {
        return flag;
    }

    // AddOrUpdate扩展（AddOrUpdate方法完成后进行）
    @Override
    protected <T> boolean extendAddOrUpdate(Boolean flag, T modelBean, boolean update, String key, Long userId) {
        return flag;
    }

    // AddOrUpdate批量操作扩展（AddOrUpdate方法完成后进行）
    @Override
    protected <T> boolean extendAddOrUpdate(Boolean flag, List<T> modelBean, boolean update, String key, Long userId) {
        return flag;
    }

    @Override
    public <T> Result addOrUpdate(T modelBean, boolean update) {
        return super.addOrUpdate(modelBean, update);
    }

    public <T> Result addOrUpdDictItem(SysSensitiveWordModel modelBean) {
        Map<String, Object> extendModel = new HashMap<>();
        extendModel.put("model", modelBean);
        extendModel.put("userId", Web.Util.getSessionUserId(request));
        extendModel.put("userName", Web.Util.getSessionUserName(request));
        return SensitiveWordHandlerUtil.addDictItem(null, null, extendModel);// 刷新敏感词
    }

    public <T> Result delDictItem(String id) {
        Map<String, Object> extendModel = new HashMap<>();
        extendModel.put("userId", Web.Util.getSessionUserId(request));
        extendModel.put("userName", Web.Util.getSessionUserName(request));
        return SensitiveWordHandlerUtil.delDictItem(null, id, extendModel);// 刷新敏感词 // 刷新敏感词
    }

    /**
     * 获取设置信息
     * 
     * @Title getSetInfo
     * @author 吕凯
     * @date 2019年10月29日 上午10:40:53
     * @param request
     *            void
     */
    public void getSetInfo(HttpServletRequest request) {
        URL url = SensitiveWordService.CONFIG.getURL();
        request.setAttribute("url", url);
        request.setAttribute("protocol", url.getProtocol());
        request.setAttribute("service", SensitiveWordHandlerUtil.getService().getClass().getName());
        request.setAttribute("configs", SensitiveWordHandlerUtil.getSetInfo());
    }

    /**
     * 
     * 创建配置文件
     * 
     * @Title createConfigFile
     * @author 吕凯
     * @date 2019年10月30日 下午3:51:53
     * @param request
     *            void
     */
    public Result createConfigFile() {
        Result result = SensitiveWordHandlerUtil.createConfigFile();
//        System.out.println("getURL==" + SensitiveWordHandlerUtil.CONFIG.getURL());
        if (!result.getSuccess()) {
            return Web.Response.result(result);
        }
        return Web.Response.success("创建配置文件成功，请刷新！");
    }

    /**
     * 获取字典库的信息
     * 
     * @Title getDictionarys
     * @author 吕凯
     * @date 2019年10月29日 上午10:41:04
     * @param request
     *            void
     */
    public void getDictionarys(HttpServletRequest request) {
        request.setAttribute("dicts_embed", SensitiveWordHandlerUtil.getService().getDictsEmbedAll());
        request.setAttribute("dicts_ext", SensitiveWordHandlerUtil.getService().getDictsExtLoad());
    }

    public String getServiceType() {
        return SensitiveWordHandlerUtil.getServiceType();
    }

    /**
     * 分页搜索字典词条
     * 
     * @Title getDictionaryItemPageBean
     * @author 吕凯
     * @date 2019年10月29日 下午2:23:30
     * @param request
     * @return PageNavigationBean<DictionaryItem>
     */
    public PageBean<DictionaryItem> getDictionaryItemPageBean(HttpServletRequest request) {
        int pageNum = getInt("p");

        String dictName = getString("dict");
        String wordSearch = getString("word");
        String typeSearch = getString("type");
        DictionaryItem itemQueryModel = new DictionaryItem();
        itemQueryModel.setWord(wordSearch);
        if (StringUtils.isNotEmpty(typeSearch)) {
            itemQueryModel.setType(ClassUtil.obj2int(typeSearch));
        } else {
            itemQueryModel.setType(SensitiveWordService.INT_NULL);
        }
        itemQueryModel.setDictionaryName(dictName);

        QueryModel queryModel = getSearchQueryModel(request);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("queryModel", queryModel);

        PageBean<DictionaryItem> pageBean = SensitiveWordHandlerUtil.getDictionaryItemPageBean(itemQueryModel, paramsMap, pageNum,
                PAGE_SIZE);
        request.setAttribute("pageBean", pageBean);

        return pageBean;
    }

    /**
     * 检查字段
     * 
     * @Title check
     * @author 吕凯
     * @date 2019年10月29日 下午2:37:20
     * @return SensitiveWordResult
     */
    public SensitiveWordResult check(HttpServletRequest request) {
        String text = getString("text");
        SensitiveWordResult result = check(text);
        request.setAttribute("model", result);
        return result;
    }

    public SensitiveWordResult check(String text) {
        SensitiveWordResult result = SensitiveWordHandlerUtil.check(text);
        return result;
    }

    /**
     * 保存词条
     * 
     * @Title addOrUpdateDictItem
     * @author 吕凯
     * @date 2019年10月29日 下午4:06:05
     * @param modelBean
     * @param update
     * @return Result
     */
    public Result addOrUpdateDictItem(SysSensitiveWordModel modelBean, boolean update) {
        String dictPath = getString("dict"); // 字典库地址
        DictionaryItem item = new DictionaryItem();
        item.setWord(modelBean.getWord());
        item.setReplaceWord(modelBean.getReplaceWord());
        item.setType(modelBean.getType());
        Map<String, Object> map = new HashMap<>();
        map.put("model", modelBean);
        Result result = SensitiveWordHandlerUtil.addDictItem(dictPath, item, map);
        if (!result.getSuccess()) {
            return Web.Response.result(result);
        }
        return Web.Response.success("添加成功！");
    }

    /**
     * 重载字典库
     * 
     * @Title reloadDicts
     * @author 吕凯
     * @date 2019年10月29日 下午5:02:00
     * @return Result
     */
    public Result reloadDicts() {
        SensitiveWordHandlerUtil.loadDict();
        return Web.Response.success("重新加载成功！");
    }

    /**
     * 重载服务类
     * 
     * @Title reloadService
     * @author 吕凯
     * @date 2019年10月31日 上午11:38:33
     * @return Result
     */
    public Result reloadService() {
        SensitiveWordHandlerUtil.reloadService();
        return Web.Response.success("重新加载成功！");
    }

    /**
     * 删除条目
     * 
     * @Title delDictItem
     * @author 吕凯
     * @date 2019年10月29日 下午5:02:10
     * @return Result
     */
    public Result delDictItem() {
        String dictPath = getString("dict"); // 字典库地址
        String word = getString("word"); // 字典库地址
        Result result = SensitiveWordHandlerUtil.delDictItem(dictPath, word);
        return result;
    }

    /**
     * 根据key获取配置属性
     * 
     * @Title getProperties
     * @author 吕凯
     * @date 2019年10月30日 上午8:49:10
     * @param key
     * @return PropertiesPojo
     */
    public PropertiesPojo getProperties(HttpServletRequest request, String key) {
        PropertiesPojo model = SensitiveWordHandlerUtil.getProperties(key); // 获取当前配置
        request.setAttribute("model", model);
        Set<String> serviceTypeKeys = SensitiveWordHandlerUtil.getServiceTypeKeys(); // 获取所有支持的字典库类型
        request.setAttribute("serviceTypeKeys", serviceTypeKeys);
        Set<String> dictsAllEmbed = SensitiveWordHandlerUtil.getDictionarysAllEmbed();
        request.setAttribute("dictsAllEmbed", dictsAllEmbed);
        Map<String, Boolean> dictsAllEmbedMap = new LinkedHashMap<>();
        dictsAllEmbed.stream().forEach(dictEmbed -> {
            if (model.getValue().contains(dictEmbed)) {
                dictsAllEmbedMap.put(dictEmbed, true);
            } else {
                dictsAllEmbedMap.put(dictEmbed, false);
            }
        });
        request.setAttribute("dictsAllEmbedMap", dictsAllEmbedMap); // 内置库及选中状态

        Set<String> handlerTypeKeys = SensitiveWordHandlerUtil.getHandlerTypeKeys(); // 支持的工厂key算法
        request.setAttribute("handlerTypeKeys", handlerTypeKeys);
        return model;
    }

    /**
     * 更新配置
     * 
     * @Title updateProperties
     * @author 吕凯
     * @date 2019年10月30日 上午8:53:45
     * @return Result
     */
    public Result updateProperties() {
        String key = getString("key");
        String value = getString("value");
        String msg = "";
        if (value == null) {
            value = "";
        }
        Result result = SensitiveWordHandlerUtil.updateProperties(key, value);
        if (SensitiveWordService.CONFIG_SERVICE_TYPE.equals(key)) {
            SensitiveWordHandlerUtil.reloadService();
        }
        SensitiveWordHandlerUtil.loadDict(); // 重新加载字典库
        if (SensitiveWordService.CONFIG_SERVICE_TYPE.equals(key) && SensitiveWordServiceType.DATABASE.getValue().equals(value)) { // 数据库检查
            Result tableResult = checkTable();
            if (!tableResult.getSuccess()) { // 表不存在，需要先创建
                msg += " 表不存在，请先创建！";
            }
        }
        if (!result.getSuccess()) {
            return Web.Response.error(result.getMessage() + msg);
        }
        return Web.Response.success("更新配置成功！" + msg);
    }

    /**
     * 检查表是否存在，存在时result.getSuccess()为true，不存在为false
     * 
     * @Title checkTable
     * @author 吕凯
     * @date 2019年10月31日 下午5:22:20
     * @return Result
     */
    public Result checkTable() {
        String tableName = TableNameUtil.getTableName(SysSensitiveWordModel.class);
        return super.checkTable(tableName);
    }

    /**
     * 创建表
     * 
     * @Title createTable
     * @author 吕凯
     * @date 2019年10月31日 下午5:22:32
     * @return Result
     */
    public Result createTable() {
        return super.createTable("/sql/sensitiveword_create.sql");
    }

}
